package com.shimao.celnet.payment.controller.api;


import com.baiwang.bop.respose.entity.InvoiceQueryResponse;
import com.shimao.celnet.payment.common.exception.BaseException;
import com.shimao.celnet.payment.controller.apinotcheck.CallOut_invOpenOutController;
import com.shimao.celnet.payment.controller.apinotcheck.CallOut_invOpenRetInfoOutController;
import com.shimao.celnet.payment.controller.apinotcheck.CallOut_invPdfOutController;
import com.shimao.celnet.payment.controller.apinotcheck.CallOut_invoiceQueryOutController;
import com.shimao.celnet.payment.model.PInvoiceBlue;
import com.shimao.celnet.payment.model.PInvoiceBlueDetail;
import com.shimao.celnet.payment.model.PInvoiceRed;
import com.shimao.celnet.payment.model.PInvoiceRedDetail;
import com.shimao.celnet.payment.model.request.CallIn_OutInvOpenRedDetailReqIn;
import com.shimao.celnet.payment.model.request.CallIn_OutInvOpenRedReqIn;
import com.shimao.celnet.payment.model.response.ErrorInfoEnum;
import com.shimao.celnet.payment.model.response.ResponseJson;
import com.shimao.celnet.payment.service.BInvoiceCompanyService;
import com.shimao.celnet.payment.service.PInvoiceBlueService;
import com.shimao.celnet.payment.service.PInvoiceRedService;
import com.shimao.celnet.payment.service.SCodeNameService;
import com.shimao.celnet.payment.util.FinalUtil;
import com.shimao.celnet.payment.util.MyDateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 外部系统 → 支付系统，数据：请求开红票信息
 * 返回给外部系统receiptGuid，
 * 2017/12/14
 * stan
 */
@RestController
@RequestMapping(value = "/invoice")
@Api("接口：pay-161(红票)-外部开票申请<outInvOpenBuleReq> 外部系统 → 支付系统，数据：开票详细信息")
public class CallIn_outInvOpenRedReqInController {
    protected Logger logger = Logger.getLogger(this.getClass());


    @Autowired//开票申请
    private PInvoiceRedService pInvoiceRedSevice;

    @Autowired//开票申请
    private PInvoiceBlueService pInvoiceBlueService;


    @Autowired//参数表
    private SCodeNameService sCodeNameService;

    @Autowired//开票公司
    private BInvoiceCompanyService bInvoiceCompanyService;

    @Autowired
    private CallOut_invOpenOutController callOut_invOpenOutController;

    @Autowired
    private CallOut_invoiceQueryOutController callOut_invoiceQueryOutController;

    @Autowired
    private CallOut_invOpenRetInfoOutController callOut_invOpenRetInfoOutController;

    @Autowired
    private CallOut_invPdfOutController callOut_invPdfOutController;

    /**
     * 外部系统开票申请
     *
     * @param requestJson
     * @throws BaseException
     */
    @ApiOperation("获取外部请求开票数据")
    @RequestMapping(value = "/invReqRed", method = RequestMethod.POST)
    public String OutInvOpenBuleReqIn(@RequestBody @Valid CallIn_OutInvOpenRedReqIn requestJson, BindingResult result) throws IOException, ParseException, BaseException {
        ResponseJson retJson = new ResponseJson(ErrorInfoEnum.SUCCESS, "");

        logger.info("pay-161-外部开票申请<outInvOpenBuleReq>请求JSON:" + requestJson.toString());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //通过valid验证
        if (result.hasErrors()) {
            for (FieldError error : result.getFieldErrors()) {
                logger.debug("缺少必要参数：" + error.getDefaultMessage());
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, error.getDefaultMessage());
                return retJson.toString();
            }
        }

        PInvoiceRed pInvoiceRed = new PInvoiceRed();//定义开红票记录对象
        List<PInvoiceRedDetail> pInvoiceRedDetailList = new ArrayList<PInvoiceRedDetail>();//定义开红票记录明细
        String receiptGuid = pInvoiceRedSevice.getGuid();//生成开票记录guid
        retJson.addBody("receiptGuid", receiptGuid);//将开票记录guid返回给请求的外部系统
        pInvoiceRed.setGuid(receiptGuid);
        pInvoiceRed.setAllFlg(requestJson.getAllFlg());//是否全部红冲 0非 1是
        pInvoiceRed.setInvoiceType(FinalUtil.INVOICE_RED);//红票
        pInvoiceRed.setInvlidFlg(FinalUtil.INVLID_FLG_DEFAULT);//作废标记默认为0，未作废
        pInvoiceRed.setInvoicePrintFlg(FinalUtil.INVLID_FLG_DEFAULT);//打印标记默认为：0未打印
        pInvoiceRed.setInvoiceStatus(FinalUtil.INVLID_RED_APPLY);//发票状态；外部请求开票
        pInvoiceRed.setSerialNo(sCodeNameService.getInvoiceSellerNumber());//serialNo开票流水号；不在接口中传递，支付系统自己生成
        String appKey = request.getHeader(FinalUtil.HEADER_APP_KEY);//获取header中的app_key
        String interfaceId = request.getHeader(FinalUtil.HEADER_INTERFACE_ID);//获取header中的interface_id
        pInvoiceRed.setAppKey(appKey);//外部系统来源
        pInvoiceRed.setInterfaceId(interfaceId);//外部系统请求接口
        if (FinalUtil.INVLID_RED_PART.equals(requestJson.getAllFlg())) {
            //业务检查，部分红冲时
            if (StringUtils.isEmpty(requestJson.getBusinessType())) {
                //业务类型
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, "业务类型【businessType】");
                return retJson.toString();
            } else if (StringUtils.isEmpty(requestJson.getInvoiceTypeCode())) {
                //发票种类编码
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, "发票种类编码【InvoiceTypeCode】");
                return retJson.toString();
            } else if (StringUtils.isEmpty(requestJson.getInvoiceSpecialMark())) {
                //特殊票种标记
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, "特殊票种标记【invoiceSpecialMark】");
                return retJson.toString();
            } else if (StringUtils.isEmpty(requestJson.getInvoiceListMark())) {
                //清单标志
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, "清单标志【InvoiceListMark】");
                return retJson.toString();
            } else if (StringUtils.isEmpty(requestJson.getOriginalInvoiceCode())) {
                //原发票代码
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, "原发票代码【originalInvoiceCode】");
                return retJson.toString();
            } else if (StringUtils.isEmpty(requestJson.getOriginalInvoiceNo())) {
                //原发票号码
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, "原发票号码【originalInvoiceNo】");
                return retJson.toString();
            } else if (StringUtils.isEmpty(requestJson.getTaxationMode())) {
                //征税方式
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, "征税方式【taxationMode】");
                return retJson.toString();
            } else if (StringUtils.isEmpty(requestJson.getInvoiceTotalPriceTax())) {
                //红冲金额合计
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, "红冲金额合计【invoiceTotalPriceTax】");
                return retJson.toString();
            } else if (requestJson.getInvoiceDetailsList().size() < 1) {
                //商品明细
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, "商品明细中缺少必填字段【InvoiceDetailsList】");
                return retJson.toString();
            }

            pInvoiceRed.setBusinessType(requestJson.getBusinessType());//业务类型
            pInvoiceRed.setEstateSfGuid(requestJson.getEstateId());//小区estateSfGuid
            //pInvoiceRed.setEstatename(requestJson.getEstateName());//小区名称
            pInvoiceRed.setDeviceType(requestJson.getDeviceType());//设备类型deviceType
            pInvoiceRed.setInvoiceTypeCode(requestJson.getInvoiceTypeCode());//发票种类
            pInvoiceRed.setInvoiceYerminalCode(requestJson.getInvoiceTerminalCode());//开票点编码
            pInvoiceRed.setInvoiceSpecialMark(requestJson.getInvoiceSpecialMark());//特殊票种标记
            //销方单位税号:：根据小区sfguid从开票公司表中取得
            if (bInvoiceCompanyService.getCompanyByEstateSFGuid(requestJson.getEstateId()) == null) {
                return new ResponseJson(ErrorInfoEnum.ERROR_PARAMS, "世茂无此小区：" + requestJson.getEstateId()).toString();
            }
            //取得销方税号
            pInvoiceRed.setSellerTaxNo(bInvoiceCompanyService.getCompanyByEstateSFGuid(requestJson.getEstateId()).getSellerTaxNo());
            pInvoiceRed.setBuyerName(requestJson.getBuyerName());//购方单位名称
            pInvoiceRed.setBuyerBankAccount(requestJson.getBuyerBankAccount());// 购方开户行及账号，专票必填
            pInvoiceRed.setBuyerTaxNo(requestJson.getBuyerTaxNo());// * 购方单位税号
            pInvoiceRed.setBuyerAddressPhone(requestJson.getBuyerAddressPhone());// 购方地址及电话，专票必填，即时开票标识为1时必须
            pInvoiceRed.setInvoiceStartTime(MyDateUtil.getReportFileStrDate());//开票开始时间
            pInvoiceRed.setBuyerEmail(requestJson.getBuyerEmail());//购方邮箱
            pInvoiceRed.setBuyerPhone(requestJson.getBuyerPhone());//购方电话
            pInvoiceRed.setDrawer(requestJson.getDrawer());//开票人
            pInvoiceRed.setChecker(requestJson.getChecker());
            pInvoiceRed.setPayee(requestJson.getPayee());
            pInvoiceRed.setInvoiceListMark(requestJson.getInvoiceListMark());//清单标志
            pInvoiceRed.setOriginalInvoiceCode(requestJson.getOriginalInvoiceCode());//原发票代码
            pInvoiceRed.setOriginalInvoiceNo(requestJson.getOriginalInvoiceNo());//原发票号码
            pInvoiceRed.setTaxationMode(requestJson.getTaxationMode());//征税方式
            pInvoiceRed.setDeductibleAmount(requestJson.getDeductibleAmount());//扣除金额
            pInvoiceRed.setInvoiceTotalPriceTax(requestJson.getInvoiceTotalPriceTax());//红冲金额合计
            pInvoiceRed.setTaxDiskNo(requestJson.getTaxDiskNo());//税控盘-编号
            pInvoiceRed.setTaxDiskKey(requestJson.getTaxDiskKey());//税控盘-口令
            pInvoiceRed.setTaxDiskPassword(requestJson.getTaxDiskPassword());//税控盘-密码
            pInvoiceRed.setRemarks(requestJson.getRemarks());//备注
            pInvoiceRed.setUserName(requestJson.getUserName());//业主名
            pInvoiceRed.setHouseName(requestJson.getHouseName());//房源名称
            pInvoiceRed.setHouseSfId(requestJson.getHouseSfId());//房源sfid
            pInvoiceRed.setRedInfoNo(requestJson.getRedInfoNo()); //红字信息表编号（给专票用的，专票的红冲时使用)
            pInvoiceRed.setNotificationNo(requestJson.getRedInfoNo()); //通知单编号（给专票用的，专票的红冲时使用)
            //开票明细
            List<CallIn_OutInvOpenRedDetailReqIn> pInvoiceDetailsList = requestJson.getInvoiceDetailsList();
            //对开票记录的明细list遍历
            if (pInvoiceDetailsList != null && pInvoiceDetailsList.size() > 0) {
                for (CallIn_OutInvOpenRedDetailReqIn invoiceDetail : pInvoiceDetailsList) {
                    PInvoiceRedDetail pInvoiceRedDetail = new PInvoiceRedDetail();//定义开票记录明细对象
                    pInvoiceRedDetail.setGoodsLineNo(invoiceDetail.getGoodsLineNo());//明细行号
                    pInvoiceRedDetail.setExsysDetailId(invoiceDetail.getExsysDetailId());//外部明细id
                    pInvoiceRedDetail.setGoodsLineNature(invoiceDetail.getGoodsLineNature());//发票行性质
                    pInvoiceRedDetail.setGoodsLineNo(invoiceDetail.getGoodsLineNo());//开票明细记录 发票行号
                    pInvoiceRedDetail.setGoodsLineNature(invoiceDetail.getGoodsLineNature());//开票明细记录 发票行性质
                    pInvoiceRedDetail.setGoodsCode(invoiceDetail.getGoodsCode());///开票明细记录 国税商品编码
                    pInvoiceRedDetail.setGoodsExtendCode(invoiceDetail.getGoodsExtendCode());///开票明细记录 自定义商品编码
                    pInvoiceRedDetail.setGoodsName(invoiceDetail.getGoodsName());//开票明细记录 商品名称
                    pInvoiceRedDetail.setGoodsSpecification(invoiceDetail.getGoodsSpecification());//开票明细记录 型号
                    pInvoiceRedDetail.setGoodsUnit(invoiceDetail.getGoodsUnit());//开票明细记录 单位
                    pInvoiceRedDetail.setGoodsQuantity(invoiceDetail.getGoodsQuantity());//开票明细记录 数量
                    pInvoiceRedDetail.setGoodsPrice(invoiceDetail.getGoodsPrice());//开票明细记录 单价
                    pInvoiceRedDetail.setGoodsTotalPrice(invoiceDetail.getGoodsTotalPrice());//开票明细记录 金额
                    pInvoiceRedDetail.setGoodsTaxRate(invoiceDetail.getGoodsTaxRate());//开票明细记录 税率
                    pInvoiceRedDetail.setPriceTaxMark(FinalUtil.INVLID_PRICE_TAX_MARK);//含税标志：默认1
                    pInvoiceRedDetail.setPreferential(invoiceDetail.getPreferentialMark());//是否使用优惠政策
                    pInvoiceRedDetail.setFreeTaxMark(invoiceDetail.getFreeTaxMark());//零税率标识：空代表无， 1 出口免税和其他免税优惠政策，2 不征增值税， 3 普通零税率”
                    pInvoiceRedDetail.setPaymentDate(invoiceDetail.getPaymentDate());//缴费时间
                    pInvoiceRedDetailList.add(pInvoiceRedDetail);
                }
            }
        } else {
            //全部红冲，取得对应蓝票信息
            Map<String, Object> retMap = pInvoiceBlueService.getInfo(requestJson.getBlueReceiptGuid());
            if(retMap.keySet().contains("erro")){
                retJson = new ResponseJson(ErrorInfoEnum.FAIL_OPEN, retMap.get("erro").toString());
                return retJson.toString();
            }
            if (retMap.size() < 1) {
                retJson = new ResponseJson(ErrorInfoEnum.ERROR_PARAMS, "原发票id【blueReceiptGuid】");
                return retJson.toString();
            }
            PInvoiceBlue pInvoiceBlue = (PInvoiceBlue) retMap.get("pInvoiceBlue");
            //如果已经进行过部分红冲，就不能进行全部红冲 /***如果需要修改，将下面的三行代码取消掉就可以*/
            if(pInvoiceBlue.getEnRedAmount() != null && pInvoiceBlue.getEnRedAmount() != ""){
                retJson = new ResponseJson(ErrorInfoEnum.FAIL_OPEN, "原发票已经红冲过，无法进行全部红冲");
                return retJson.toString();
            }
            List<PInvoiceBlueDetail> pInvoiceBlueDetailList = (List<PInvoiceBlueDetail>) retMap.get("pInvoiceDetailList");
            pInvoiceRed.setBusinessType(pInvoiceBlue.getBusinessType());//业务类型
            pInvoiceRed.setEstateSfGuid(pInvoiceBlue.getEstateSfGuid());//小区sfid
//            pInvoiceRed.setEstatename(pInvoiceBlue.getEstatename());//小区名称
            pInvoiceRed.setDeviceType(pInvoiceBlue.getDeviceType());//设备类型deviceType
            pInvoiceRed.setInvoiceTypeCode(pInvoiceBlue.getInvoiceTypeCode());//发票种类
            pInvoiceRed.setInvoiceYerminalCode(pInvoiceBlue.getInvoiceYerminalCode());//开票点编码
            pInvoiceRed.setInvoiceSpecialMark(pInvoiceBlue.getInvoiceSpecialMark());//特殊票种标记
            pInvoiceRed.setSellerTaxNo(pInvoiceBlue.getSellerTaxNo());//销方单位税号
            pInvoiceRed.setBuyerName(pInvoiceBlue.getBuyerName());//购方单位名称
            pInvoiceRed.setBuyerBankAccount(pInvoiceBlue.getBuyerBankAccount());//             购方开户行及账号，专票必填
            pInvoiceRed.setBuyerTaxNo(pInvoiceBlue.getBuyerTaxNo());//             * 购方单位税号
            pInvoiceRed.setBuyerAddressPhone(pInvoiceBlue.getBuyerAddressPhone());//             购方地址及电话，专票必填，即时开票标识为1时必须
            pInvoiceRed.setBuyerEmail(pInvoiceBlue.getBuyerEmail());//购方邮箱
            pInvoiceRed.setBuyerPhone(pInvoiceBlue.getBuyerPhone());//购方电话
            pInvoiceRed.setDrawer(pInvoiceBlue.getDrawer());//开票人
            pInvoiceRed.setChecker(pInvoiceBlue.getChecker());
            pInvoiceRed.setPayee(pInvoiceBlue.getPayee());
            pInvoiceRed.setInvoiceListMark(pInvoiceBlue.getInvoiceListMark());//清单标志
            pInvoiceRed.setOriginalInvoiceCode(pInvoiceBlue.getInvoiceCode());//原发票代码
            pInvoiceRed.setOriginalInvoiceNo(pInvoiceBlue.getInvoiceNo());//原发票号码
            pInvoiceRed.setTaxationMode(pInvoiceBlue.getTaxationMode());//征税方式
            pInvoiceRed.setDeductibleAmount(pInvoiceBlue.getDeductibleAmount());//扣除金额
            pInvoiceRed.setInvoiceTotalPriceTax(pInvoiceBlue.getInvoiceTotalPriceTax());//红冲金额合计
            pInvoiceRed.setInvoiceTotalPrice(pInvoiceBlue.getInvoiceTotalPrice());
            pInvoiceRed.setInvoiceTotalTax(pInvoiceBlue.getInvoiceTotalTax());
            pInvoiceRed.setTaxDiskNo(pInvoiceBlue.getTaxDiskNo());//税控盘-编号
            pInvoiceRed.setTaxDiskKey(pInvoiceBlue.getTaxDiskKey());//税控盘-口令
            pInvoiceRed.setTaxDiskPassword(pInvoiceBlue.getTaxDiskPassword());//税控盘-密码
            pInvoiceRed.setRemarks(pInvoiceBlue.getRemarks());//备注
            pInvoiceRed.setUserName(requestJson.getUserName());//业主名
            pInvoiceRed.setHouseName(requestJson.getHouseName());//房源名称
            pInvoiceRed.setHouseSfId(requestJson.getHouseSfId());//房源sfid
            pInvoiceRed.setInvoiceStartTime(MyDateUtil.getReportFileStrDate());//开票开始时间
            pInvoiceRed.setRedInfoNo(requestJson.getRedInfoNo()); //红字信息表编号（给专票用的，专票的红冲时使用)
            pInvoiceRed.setNotificationNo(requestJson.getRedInfoNo()); //通知单编号（给专票用的，专票的红冲时使用)
            //对开票记录的明细list遍历
            if (pInvoiceBlueDetailList != null && pInvoiceBlueDetailList.size() > 0) {
                for (PInvoiceBlueDetail invoiceDetail : pInvoiceBlueDetailList) {
                    PInvoiceRedDetail pInvoiceRedDetail = new PInvoiceRedDetail();//定义开票记录明细对象
                    pInvoiceRedDetail.setGoodsLineNo(invoiceDetail.getGoodsLineNo());//明细行号
                    pInvoiceRedDetail.setExsysDetailId(invoiceDetail.getExsysDetailId());//外部明细id
                    pInvoiceRedDetail.setGoodsLineNature(invoiceDetail.getGoodsLineNature());//发票行性质
                    pInvoiceRedDetail.setGoodsLineNo(invoiceDetail.getGoodsLineNo());//开票明细记录 发票行号
                    pInvoiceRedDetail.setGoodsLineNature(invoiceDetail.getGoodsLineNature());//开票明细记录 发票行性质
                    pInvoiceRedDetail.setGoodsCode(invoiceDetail.getGoodsCode());///开票明细记录 国税商品编码
                    pInvoiceRedDetail.setGoodsExtendCode(invoiceDetail.getGoodsExtendCode());///开票明细记录 自定义商品编码
                    pInvoiceRedDetail.setGoodsName(invoiceDetail.getGoodsName());//开票明细记录 商品名称
                    pInvoiceRedDetail.setGoodsSpecification(invoiceDetail.getGoodsSpecification());//开票明细记录 型号
                    pInvoiceRedDetail.setGoodsUnit(invoiceDetail.getGoodsUnit());//开票明细记录 单位
                    pInvoiceRedDetail.setGoodsQuantity(invoiceDetail.getGoodsQuantity());//开票明细记录 数量
                    pInvoiceRedDetail.setGoodsPrice(invoiceDetail.getGoodsPrice());//开票明细记录 单价
                    pInvoiceRedDetail.setGoodsTotalPrice(invoiceDetail.getGoodsTotalPrice());//开票明细记录 金额
                    pInvoiceRedDetail.setGoodsTotalTax(invoiceDetail.getGoodsTotalTax());
                    pInvoiceRedDetail.setGoodsTaxRate(invoiceDetail.getGoodsTaxRate());//开票明细记录 税率
                    pInvoiceRedDetail.setPriceTaxMark(FinalUtil.INVLID_PRICE_TAX_MARK);//含税标志：默认1
                    pInvoiceRedDetail.setPreferential(invoiceDetail.getPreferential());//是否使用优惠政策
                    pInvoiceRedDetail.setPaymentDate(invoiceDetail.getPaymentDate());//缴费时间
                    pInvoiceRedDetailList.add(pInvoiceRedDetail);
                }
            }
           try {
                // 1、保存红票开票记录
                pInvoiceRedSevice.save(pInvoiceRed, pInvoiceRedDetailList);
                //2、调用百望开票接口开票
                PInvoiceRed pInvoiceRedRet = callOut_invOpenOutController.invoiceRedFromRequest(pInvoiceRed);
                if (pInvoiceRedRet != null) {
                    JSONObject RetJsonObject = new JSONObject();
                    //更新蓝票信息
                    pInvoiceBlue.setRedFlg(FinalUtil.INVLID_RED_APPLY);
                    pInvoiceBlue.setRedInvoiceTotalPriceTax(pInvoiceBlue.getInvoiceTotalPriceTax());
                    pInvoiceBlue.setEnRedAmount(String.valueOf(Float.valueOf(pInvoiceBlue.getInvoiceTotalPriceTax())-Float.valueOf(pInvoiceBlue.getEnRedAmount()==null?"0":pInvoiceBlue.getEnRedAmount())));
                    pInvoiceBlueService.update(pInvoiceBlue);
                    //3、调用百望开票结果查询接口，查询开票结果
                   // InvoiceQueryResponse response = callOut_invoiceQueryOutController.invoiceRedQueryOut(pInvoiceRedRet);
                    //返回结果
                   /* if(response == null){
                        return new ResponseJson(ErrorInfoEnum.FAIL_QUERY, "发票"+pInvoiceRedRet.getGuid()).toString();
                    }*/
                    //4、开电子发票时，调研百望电子发票查询接口，获取电子发票URL
                    String strUrl = null;
                    //红冲规则：电子蓝票--》电子红票  纸质蓝票--》纸质红票
                    if (FinalUtil.INVOICE_TYPE_CODE_026.equals(pInvoiceBlue.getInvoiceTypeCode())) {
                        strUrl = callOut_invPdfOutController.invPdfOut(pInvoiceRed);
                    }
                    RetJsonObject = callOut_invOpenRetInfoOutController.invOpenRetRedInfoOut1(pInvoiceRedRet, strUrl);
                    /*if(response != null){
                        //返回结果
                        RetJsonObject = callOut_invOpenRetInfoOutController.invOpenRetRedInfoOut(response, pInvoiceRed, strUrl);
                        //return new ResponseJson(ErrorInfoEnum.FAIL_QUERY, "发票"+pInvoiceRedRet.getGuid()).toString();
                    }else {
                        //返回结果
                        RetJsonObject = callOut_invOpenRetInfoOutController.invOpenRetRedInfoOut1(pInvoiceRedRet, strUrl);
                    }*/
                    //JSONObject RetJsonObject = callOut_invOpenRetInfoOutController.invOpenRetRedInfoOut(response, pInvoiceRed, strUrl);
                    JSONObject RetJson = new JSONObject();
                    RetJson.put("errcode", "0000");
                    RetJson.put("errmsg", "处理成功");
                    RetJson.put("data", RetJsonObject);
                    //更新蓝票信息
                    pInvoiceBlue.setRedFlg(FinalUtil.INVLID_RED_SUCCESS);//红冲成功
                    pInvoiceBlueService.update(pInvoiceBlue);
                    return RetJson.toString();
                }

            } catch (Exception e) {
               logger.debug(ErrorInfoEnum.FAIL_OPEN+"  ******** "+e.getMessage());
                retJson = new ResponseJson(ErrorInfoEnum.FAIL_OPEN, e.getMessage());
            }
        }
        return retJson.toString();
    }
}
